// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.syncserver.processor;

import com.google.appengine.syncserver.endpoint.Request;
import com.google.appengine.syncserver.endpoint.Response;
import com.google.appengine.syncserver.shared.ClientIdRequest;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletResponse;

/**
 * Abstract class for all client request processors.
 */
public abstract class AbstractProcessor {

  private static final Logger log = Logger.getLogger(ClientIdRequest.class.getName());

  public final Response processSwarmRequest(Request request) {

    String reqStr = request.getPayload();
    Response response = new Response();
    if (reqStr == null) {
      response.setInternalServerError(true);
      return response;
    }

    String respStr = null;
    try {
      respStr = processRequest(reqStr);
    } catch (HttpException e) {
      // TODO(chintanraoh): rename the above exception.
      if (e.getHttpStatus() == HttpServletResponse.SC_CONFLICT) {
        log.severe("Conflict");
        response.setConflict(true);
        return response;
      }
      log.severe(e.getMessage());
    } catch (Exception e) {
      log.severe(e.getMessage());
    }
    if (respStr == null) {
      response.setInternalServerError(true);
      return response;
    }
    response.setResponseStr(respStr);
    return response;
  }

  protected abstract String processRequest(String requestString) throws Exception;
}
